// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  // 1. 找到本用户
  const usersDb = cloud.database().collection('users')
  const userData = await usersDb.where({
    openid
  }).get()
  const user = userData.data[0]
  delete user._id
  // 2. 从 comments 数据库中获取对应 bookId 并从 books 对应数目中删除该评论
  const commentsDb = cloud.database().collection('comments')
  const bookIdData = await commentsDb.where({
    commentId: event.commentId
  }).field({
    bookId: true
  }).get()
  const bookId = bookIdData.data[0].bookId
  const booksDb = cloud.database().collection('books')
  const bookData = await booksDb.where({
    bookId
  }).get()
  const book = bookData.data[0]
  delete book._id
  const newBookComments = book.comments.filter(item => event.commentId !== item.commentId)
  book.comments = newBookComments
  await booksDb.where({
    bookId
  }).update({
    data: book
  })
  // 3. 从本用户的 comments 中删除对应 comment
   const newUserComments = user.comments.filter(item => item.commentId !== event.commentId)
   user.comments = newUserComments
   await usersDb.where({
     openid
   }).update({
     data: user
   })
  // 4. 从 对应的 comments 数据库中删除该评论
  await commentsDb.where({
    commentId: event.commentId
  }).remove()
  // 5. 返回处理提示
  return {
    status: 0,
    msg: '删除成功'
  }
}